﻿using System.Collections.Generic;
using System.Linq;

namespace eProject.ViewModel.Commands
{
    public class DeleteTaskCommand : ICommand
    {
        private readonly CommonManager _manager;
        private readonly string _name;
        private readonly string _description;
        private readonly long _duration;

        private int _index;

        private bool _isCanceled;
        private bool _isExecuted;

        private IEnumerable<DeleteActivityCommand> _actsCommand;

        public DeleteTaskCommand(CommonManager manager, TaskViewModel task)
        {
            _manager = manager;
            _name = task.Name;
            _description = task.Description;
            _duration = task.Duration;
        }

        public void Execute()
        {
            if (_isExecuted) return;
            var task = _manager.GetTask(_name);
            _actsCommand = _manager.Activities.Where(a => a.Task == task).Select(a => new DeleteActivityCommand(_manager, a)).ToList();
            foreach (var command in _actsCommand)
            {
                command.Execute();
            }
            _index = _manager.Tasks.IndexOf(task);
            _manager.DeleteTask(task);
            _isExecuted = true;
            _isCanceled = false;
        }

        public void Unexecute()
        {
            if (_isCanceled) return;            
            _manager.CreateTask(_name, _description, _duration, _index);
            foreach (var command in _actsCommand)
            {
                command.Unexecute();
            }
            _isCanceled = true;
            _isExecuted = false;
        }
    }
}
